package mysql

import (
	"crypto/md5"
	"database/sql"
	"encoding/hex"
	"errors"
	"gin_study/_26_bluebell/models"
)

const (
	secret               = "wuzhuya.top"
	ErrorUserExist       = "用户已存在"
	ErrorUserNotExist    = "用户不存在"
	ErrorInvalidPassword = "用户名或密码错误"
)

func CheckUserExist(username string) (err error) {
	sqlStr := `select count(user_id) from user where username=?`
	var count int
	if err = db.Get(&count, sqlStr, username); err != nil {
		return
	}
	if count > 0 {
		err = errors.New(ErrorUserExist)
	}
	return
}

func InsertUser(user *models.User) (err error) {
	// 对密码进行加密
	user.Password = encryptPassword(user.Password)
	// 执行SQL语句入库
	sqlStr := `insert into user(user_id,username,password) value (?,?,?)`
	_, err = db.Exec(sqlStr, user.UserID, user.Username, user.Password)
	return
}

func encryptPassword(oPassword string) string {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum([]byte(oPassword)))
}

func Login(user *models.User) (err error) {
	sqlStr := `select user_id,username,password from user where username=? and password=?`
	err = db.Get(user, sqlStr, user.Username, encryptPassword(user.Password))
	if errors.Is(err, sql.ErrNoRows) {
		return errors.New(ErrorUserNotExist)
	}
	if err != nil {
		return
	}
	if user == nil {
		return errors.New(ErrorInvalidPassword)
	}
	return
}
